<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="true"
      :http-request="upLoadFn"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="FormData.staffPhoto" :src="FormData.staffPhoto" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-show="showPro" type="line" :percentage="percentage" class="progress" />
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretKey: 'yiGcliRxFKCG8oHYebNyOdgW9ZZieQ3W',
  SecretId: 'AKID1tY0FG46wXt2yhBQNFtIVWKtFZgZFhx4'
})
export default {
  props: {
    // eslint-disable-next-line vue/prop-name-casing
    FormData: {
      type: Object,
      default: () => {
        return {}
      }
    }

  },
  data() {
    return {
      // 控制进度条进程
      percentage: 0,
      // 控制进度条显隐
      showPro: false,
      imageUrl: ''
    }
  },
  created() {

  },
  methods: {
    // 上传之前的校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 自定义上传的方法
    upLoadFn(params) {
      this.showPro = true
      cos.putObject({

        Bucket: 'hr-cms-1312615728', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-beijing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
          console.log(params)
        }
      // eslint-disable-next-line handle-callback-err
      }, (err, data) => {
        if (data.statusCode === 200) {
          this.percentage = 0
          this.showPro = false
          this.$emit('change-userPhoto', `http://${data.Location}`)
        }
      })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
